import { createLogger, LogLevel, nameFromLevel } from "bunyan";
import path from "node:path";
import fs from "node:fs";
import dayjs from "dayjs";

const infoLogPath = path.resolve(path.resolve(), "./logs/info");
const errorLogPath = path.resolve(path.resolve(), "./logs/error");

if (!fs.existsSync(infoLogPath)) {
  fs.mkdirSync(infoLogPath, { recursive: true });
}
if (!fs.existsSync(errorLogPath)) {
  fs.mkdirSync(errorLogPath, { recursive: true });
}
const logger = createLogger({
  name: "koa-server",
  src: false,
  level: "info",
  streams: [
    {
      level: "info",
      type: "rotating-file",
      path: path.resolve(infoLogPath, dayjs().format("YYYY-MM-DD")),
      period: "1d",
      count: 10,
    },
    {
      level: "debug",
      stream: {
        write(obj: any) {
          let msg = obj;
          try {
            const res = JSON.parse(obj);
            msg = `${dayjs(res.time).format("MM-DD HH:mm:ss")} ${nameFromLevel[
              res.level
            ]?.toLocaleUpperCase()} ${res.msg} \n`;
          } catch (e) {
            msg = obj;
          }
          process.stdout.write(
            typeof msg === "string" ? msg : JSON.stringify(msg)
          );
        },
      },
    },
    {
      level: "error",
      type: "rotating-file",
      path: path.resolve(errorLogPath, dayjs().format("YYYY-MM-DD")),
      period: "1d",
      count: 10,
    },
  ],
});

export { logger };
